import { getData, updateData, addData } from '@vimi/utils-api'
import { getApprove } from '@/credit/mixin/wf'

const contractTableName = 'contract_approval'
const relatedTableName = 'customer_related'
const SERVICE_NAME = 'credit'

export const getContractData = queryId =>
  getData({
    table: contractTableName,
    params: {
      'customer_related_id.eq': queryId,
    },
  }).then(res => res?.data?.[0] ?? {})

export const updateContract = (id, data) => updateData(SERVICE_NAME, contractTableName, id, data)

/**
 * 添加合同审批列表
 * @param {*} data 添加数据
 */
export const addContract = data => addData(SERVICE_NAME, contractTableName, data)

export const updateRelatedContractStatus = (id, status) =>
  updateData(SERVICE_NAME, relatedTableName, id, {
    contract_approval_status: status,
  })

export const getWfKey = isUnion => (isUnion ? 'CONTRACT_APPROVAL_DIR_PRO' : 'CONTRACT_APPROVAL')

const getApproveConfig = isUnion =>
  isUnion
    ? {
        'CONTRACT_APPROVAL_DIR_PRO-RESA': {
          cmpt: 'approve-res',
          rekey: null,
        },
      }
    : {
        'CONTRACT_APPROVAL-RES': {
          cmpt: 'approve-res',
          rekey: null,
        },
        'CONTRACT_APPROVAL-RES_MANAGE': {
          cmpt: 'approve-common',
          rekey: 'CONTRACT_APPROVAL-RES',
        },
        'CONTRACT_APPROVAL-RISK': {
          cmpt: 'approve-common',
          rekey: 'CONTRACT_APPROVAL-RES',
        },
        'CONTRACT_APPROVAL-RISK_MANAGE': {
          cmpt: 'approve-common',
          rekey: 'CONTRACT_APPROVAL-RES',
        },
        'CONTRACT_APPROVAL-JURY_DIRECTOR': {
          cmpt: 'approve-common',
          rekey: 'CONTRACT_APPROVAL-RES',
        },
      }

// 获取审批流程配置信息
export const getApproveProcess = (queryId, user) => {
  const isUnion = user.scopeArr?.includes('dirGuaPro')
  const wfKey = getWfKey(isUnion)
  const config = getApproveConfig(isUnion)
  return getApprove(
    {
      wfKey,
      queryId,
      config,
    },
    user
  )
}

export const enumLoanVarieties = {
  1: '流贷',
  2: '固贷',
  3: '其他',
}
